using CommunityToolkit.Mvvm.Input;
using DesktopApp.Models;
using DesktopApp.ViewModels.Services;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;

namespace DesktopApp.ViewModels
{
    public class StatusBarViewModel : ViewModelBase
    {
        private readonly ILogProcessingService _logProcessingService;
        private readonly IStatisticsService _statisticsService;
        private readonly IUIService _uiService; // For potential error messages

        // References to other ViewModels needed for data access
        private readonly RulesViewModel _rulesViewModel;
        private readonly LogPanelViewModel _logPanelViewModel;

        // Statistics Properties
        private int _originalLineCount = 0;
        public int OriginalLineCount
        {
            get => _originalLineCount;
            private set => SetProperty(ref _originalLineCount, value);
        }

        private int _resultLineCount = 0;
        public int ResultLineCount
        {
            get => _resultLineCount;
            private set => SetProperty(ref _resultLineCount, value);
        }

        private string _reductionRateText = "精简率: N/A";
        public string ReductionRateText
        {
            get => _reductionRateText;
            private set => SetProperty(ref _reductionRateText, value);
        }

        private string _ruleStatsText = "启用: 0 / 总计: 0";
        public string RuleStatsText
        {
            get => _ruleStatsText;
            private set => SetProperty(ref _ruleStatsText, value);
        }

        private string _appliedRulesSummary = "已应用: 无";
        public string AppliedRulesSummary
        {
            get => _appliedRulesSummary;
            private set => SetProperty(ref _appliedRulesSummary, value);
        }

        // Processing Command
        public ICommand ProcessCommand { get; }

        public StatusBarViewModel(
            ILogProcessingService logProcessingService,
            IStatisticsService statisticsService,
            IUIService uiService,
            RulesViewModel rulesViewModel,      // Inject RulesViewModel
            LogPanelViewModel logPanelViewModel) // Inject LogPanelViewModel
        {
            _logProcessingService = logProcessingService;
            _statisticsService = statisticsService;
            _uiService = uiService;
            _rulesViewModel = rulesViewModel;
            _logPanelViewModel = logPanelViewModel;

            // Initialize Command
            ProcessCommand = new AsyncRelayCommand(ProcessLogs, CanProcessLogs);

            // Subscribe to events from other VMs to trigger stat updates
            _logPanelViewModel.LogTextChanged += (s, e) => RecalculateLogStatistics();
            _rulesViewModel.RulesChangedForStats += (s, e) => RecalculateRuleStatistics();

            // Initial calculation
            RecalculateLogStatistics();
            RecalculateRuleStatistics();
            // REMOVED: Initial notification moved effectively to the end of RulesViewModel loading via event.
        }

        // Statistics Update Methods
        public void RecalculateRuleStatistics()
        {
            // Access rules directly from the injected RulesViewModel
            var stats = _statisticsService.CalculateRuleStats(_rulesViewModel.Rules);
            RuleStatsText = $"启用: {stats.EnabledCount} / 总计: {stats.TotalCount}";
            AppliedRulesSummary = _statisticsService.GenerateAppliedRulesSummary(_rulesViewModel.Rules);
            Debug.WriteLine("StatusBarViewModel: Rule statistics recalculated.");
            // Temporarily comment out for isolation
            // (ProcessCommand as AsyncRelayCommand)?.NotifyCanExecuteChanged();
            // ADDED: Notify ProcessCommand when rule stats change
            // (ProcessCommand as AsyncRelayCommand)?.NotifyCanExecuteChanged();
        }

        public void RecalculateLogStatistics()
        {
            // Access log text directly from the injected LogPanelViewModel
            OriginalLineCount = _statisticsService.CalculateLineCount(_logPanelViewModel.OriginalLogText);
            ResultLineCount = _statisticsService.CalculateLineCount(_logPanelViewModel.ResultLogText);

            var percentage = _statisticsService.CalculateReductionPercentage(OriginalLineCount, ResultLineCount);
            ReductionRateText = percentage.HasValue ? $"精简率: {percentage.Value:F0}%" : "精简率: N/A";
            Debug.WriteLine("StatusBarViewModel: Log statistics recalculated.");
            // Add logging before notification
            Debug.WriteLine("[StatusBarViewModel] RecalculateLogStatistics: About to call NotifyCanExecuteChanged for ProcessCommand.");
            // Process command CanExecute might change based on OriginalLogText
            (ProcessCommand as AsyncRelayCommand)?.NotifyCanExecuteChanged();
        }

        // Command Execution Methods
        private async Task ProcessLogs()
        {
            if (!CanProcessLogs()) return;
            Debug.WriteLine("StatusBarViewModel: ProcessLogs command executing...");

            // Get active rules from RulesViewModel
            var activeRules = _rulesViewModel.Rules.Where(r => r.IsEnabled).ToList();
            // Get original log from LogPanelViewModel
            var originalLog = _logPanelViewModel.OriginalLogText;

            // Indicate busy state if desired
            // IsBusy = true;
            try
            {
                 // Call the processing service
                 string resultLog = await _logProcessingService.ProcessLogAsync(originalLog, activeRules);
                 Debug.WriteLine("StatusBarViewModel: Log processing service call complete.");
                 // Update ResultLogText in LogPanelViewModel
                 _logPanelViewModel.ResultLogText = resultLog;
                 // Statistics are updated automatically because ResultLogText setter in LogPanelVM raises LogTextChanged event
            }
            catch (Exception ex)
            {
                 Debug.WriteLine($"StatusBarViewModel: Error calling LogProcessingService: {ex.Message}");
                 // Show error in result pane or via dialog
                 _logPanelViewModel.ResultLogText = $"处理时发生错误: {ex.Message}";
            }
            finally
            {
                 // IsBusy = false;
            }
        }

        private bool CanProcessLogs()
        {
            // Check both original log text and if any rules are enabled
            bool hasLog = !string.IsNullOrEmpty(_logPanelViewModel.OriginalLogText);
            bool hasEnabledRules = _rulesViewModel.Rules.Any(r => r.IsEnabled);
            // Depends on whether there's original log text
            Debug.WriteLine($"[StatusBarViewModel] CanProcessLogs: hasLog={hasLog}, hasEnabledRules={hasEnabledRules}");
            return hasLog && hasEnabledRules;
        }
    }
} 